import axios from 'axios'
import Qs from 'qs'
import router from '@/router/index'
import store from '@/store/index'
import { Notification, MessageBox, Message } from 'element-ui'

const toLogin = () => {
    router.push({
        path: '/login',
        query: {
            redirect: router.currentRoute.fullPath
        }
    })
}

axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded'

const api = axios.create({
    baseURL: process.env.VUE_APP_API_ROOT,
    timeout: 30000,
    responseType: 'json'
    // withCredentials: true
})

api.interceptors.request.use(
    request => {
        if (request.method == 'post') {
            if (request.data instanceof FormData) {
                if (store.getters['user/isLogin']) {
                    // 如果是 FormData 类型（上传图片）
                    request.data.append('token', store.state.user.token)
                }
            } else {
                // 带上 token
                if (request.data == undefined) {
                    request.data = {}
                }
                if (store.getters['user/isLogin']) {
                    request.data.token = store.state.user.token
                }
                request.data = Qs.stringify(request.data)
            }
        } else {
            // 带上 token
            if (request.params == undefined) {
                request.params = {}
            }
            if (store.getters['user/isLogin']) {
                request.params.token = store.state.user.token
            }
        }
        return request
    }
)

// 响应拦截器
api.interceptors.response.use(res => {
    // 未设置状态码则默认成功状态
    const code = res.status || 200;
    // 获取错误信息
    const message = res.data.msg || '服务异常！'
    if (code === 401) {
        MessageBox.confirm('登录状态已过期，您可以继续留在该页面，或者重新登录', '系统提示',
            {
                confirmButtonText: '重新登录',
                cancelButtonText: '取消',
                type: 'warning'
            }
        ).then(() => {
            store.dispatch('Logout').then(() => {
                location.reload() // 为了重新实例化vue-router对象 避免bug
            })
        })
    } else if (code === 500) {
        Message({
            message: message,
            type: 'error'
        })
        return Promise.reject(new Error(message))
    } else if (code !== 200) {
        Notification.error({
            title: message
        })
        return Promise.reject('error')
    } else {
        return res.data
    }
},
error => {
    Message({
        message: error.message,
        type: 'error',
        duration: 3 * 1000
    })
    return Promise.reject(error)
})

export default api
